package com.github.cyf.service;

import com.github.cyf.common.util.ExecutorUtil;
import com.github.cyf.task.MdcRunnable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.Executor;

/**
 * @author chenyifan
 * @create 2024-09-02 17:29
 */
@Service
@Slf4j
public class TestService {
    private final Executor threadPool;

    public TestService(@Qualifier("threadPoolTaskExecutor") Executor threadPool) {
        this.threadPool = threadPool;
    }

    public void test1() {
        log.info("sync test in service");
    }

    public void test2() {
        Thread subThread = new Thread(() -> log.info("subThread test in service"));
        subThread.setName("子线程");
        subThread.start();
        try {
            subThread.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            subThread.stop();
        }
    }

    @Async("threadPoolTaskExecutor")
    public void test3() {
        log.info("async test in service");
    }

    @Async("mdcThreadPoolTaskExecutor")
    public void test4() {
        log.info("async test in service");
    }

    public void test5() {
        ExecutorUtil.syncExecute(threadPool, new MdcRunnable(() -> log.info("async test in service")));
    }
}
